package com.xiaoma.tpo.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xiaoma.tpo.dao.UserDao;
import com.xiaoma.tpo.domain.User;
import com.xiaoma.tpo.resource.TPOConstants;
import com.xiaoma.tpo.service.UserService;

@Controller
@RequestMapping("/sys/teacher")
public class TeacherController {
    public static final String CURRENT_USER = "CURRENT_USER";
    
    @Autowired
    private UserDao userDao;
    
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String index(){
        return "forumJJ/login";
        
    }
    
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(@RequestParam String name, @RequestParam String password, HttpSession session){
        String location = "redirect:/sys/teacher/main";
        String base64Pwd = new String(Base64.encodeBase64(password.getBytes()));
        User user = findByNameAndPwd(name, base64Pwd);
        if(user != null && ((user.getRole().intValue() == TPOConstants.TEACHER) || (user.getRole().intValue() == TPOConstants.ADMIN))){
            session.setAttribute(CURRENT_USER, user);
        } else {
            location = "forumJJ/login";
        }
        return location;
        
    }
    
    @RequestMapping(value="/main", method = RequestMethod.GET)
    public String main(HttpSession session, Model model) {
        return "forumJJ/main";
    }
    
    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public String logout(HttpSession session){
        session.removeAttribute(CURRENT_USER);
        return "redirect:/sys/teacher/login";
        
    }
    
    @RequestMapping(value = "/list",method = RequestMethod.POST)
    @ResponseBody
    public List<User> getTeachers(){
        User entity = new User();
        entity.setRole(2);
        List<User> teachers = userDao.findByColumns(entity);
        return teachers;
        
    }
    
    private User findByNameAndPwd(String name, String password) {
        User entity = new User();
        entity.setName(name);
        entity.setPassword(password);
        List<User> users = userDao.findByColumns(entity);
        return users.size() > 0 ? users.get(0) : null;
    }
    
}
